{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'1.4.0'"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"\"\"A very simple MNIST classifier.\n",
    "See extensive documentation at\n",
    "https://www.tensorflow.org/get_started/mnist/beginners\n",
    "\"\"\"\n",
    "from __future__ import absolute_import\n",
    "from __future__ import division\n",
    "from __future__ import print_function\n",
    "\n",
    "import argparse\n",
    "import sys\n",
    "import tensorflow as tf\n",
    "tf.__version__"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "我们在这里调用系统提供的Mnist数据函数为我们读入数据，如果没有下载的话则进行下载。\n",
    "\n",
    "<font color=#ff0000>**这里将data_dir改为适合你的运行环境的目录**</font>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Extracting mnist_data\\train-images-idx3-ubyte.gz\n",
      "Extracting mnist_data\\train-labels-idx1-ubyte.gz\n",
      "Extracting mnist_data\\t10k-images-idx3-ubyte.gz\n",
      "Extracting mnist_data\\t10k-labels-idx1-ubyte.gz\n"
     ]
    }
   ],
   "source": [
    "# Import data\n",
    "from tensorflow.examples.tutorials.mnist import input_data\n",
    "data_dir = 'mnist_data'\n",
    "mnist = input_data.read_data_sets(data_dir, one_hot=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "一个非常非常简陋的模型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Define loss and optimizer\n",
    "x = tf.placeholder(tf.float32, [None, 784])\n",
    "y_ = tf.placeholder(tf.float32, [None, 10])\n",
    "learning_rate = tf.placeholder(tf.float32)\n",
    "\n",
    "with tf.name_scope('reshape'):\n",
    "  x_image = tf.reshape(x, [-1, 28, 28, 1])\n",
    "\n",
    "# First convolutional layer - maps one grayscale image to 32 feature maps.\n",
    "with tf.name_scope('conv1'):\n",
    "  h_conv1 = tf.layers.conv2d(x_image, 32, [6,6],\n",
    "                             padding='SAME',\n",
    "                             kernel_initializer=tf.truncated_normal_initializer(stddev=0.01),\n",
    "                             activation=tf.nn.relu)\n",
    " \n",
    "\n",
    "# Pooling layer - downsamples by 2X.\n",
    "with tf.name_scope('pool1'):\n",
    "  h_pool1 = tf.layers.max_pooling2d(h_conv1, pool_size=[6,6],\n",
    "                        strides=[2, 2], padding='VALID')\n",
    "\n",
    "# Second convolutional layer -- maps 32 feature maps to 64.\n",
    "with tf.name_scope('conv2'):\n",
    "  h_conv2 = tf.layers.conv2d(h_pool1, 64, [6,6],\n",
    "                             padding='SAME',\n",
    "                             kernel_initializer=tf.truncated_normal_initializer(stddev=0.01),\n",
    "                             activation=tf.nn.relu)\n",
    "\n",
    "# Second pooling layer.\n",
    "with tf.name_scope('pool2'):\n",
    "  h_pool2 = tf.layers.max_pooling2d(h_conv2, pool_size=[2,2],\n",
    "                        strides=[2, 2], padding='VALID')\n",
    "\n",
    "# Fully connected layer 1 -- after 2 round of downsampling, our 28x28 image\n",
    "# is down to 7x7x64 feature maps -- maps this to 1024 features.\n",
    "with tf.name_scope('fc1'):\n",
    "  h_pool2_flat = tf.layers.flatten(h_pool2)\n",
    "  h_fc1 = tf.layers.dense(h_pool2_flat, \n",
    "                          units=1024,\n",
    "                          kernel_initializer=tf.truncated_normal_initializer(stddev=0.01), \n",
    "                          activation=tf.nn.relu)\n",
    "\n",
    "# Dropout - controls the complexity of the model, prevents co-adaptation of\n",
    "# features.\n",
    "with tf.name_scope('dropout'):\n",
    "  keep_prob = tf.placeholder(tf.float32)\n",
    "  h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)\n",
    "\n",
    "# Map the 1024 features to 10 classes, one for each digit\n",
    "with tf.name_scope('fc2'):\n",
    "  y = tf.layers.dense(h_fc1_drop, 10, activation=None)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "接下来我们计算交叉熵，注意这里不要使用注释中的手动计算方式，而是使用系统函数。\n",
    "另一个注意点就是，softmax_cross_entropy_with_logits的logits参数是**未经激活的wx+b**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "cross_entropy = tf.reduce_mean(\n",
    "    tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))\n",
    "\n",
    "l2_loss = tf.add_n( [tf.nn.l2_loss(w) for w in tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)] )\n",
    "total_loss = cross_entropy + 7e-5*l2_loss\n",
    "train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(total_loss)\n",
    "\n",
    "sess = tf.Session()\n",
    "init_op = tf.global_variables_initializer()\n",
    "sess.run(init_op)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "在这里我们仍然调用系统提供的读取数据，为我们取得一个batch。\n",
    "然后我们运行3k个step(5 epochs)，对权重进行优化。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "step 100, entropy loss: 1.745929, l2_loss: 105.647812, total loss: 1.753325\n",
      "0.56\n",
      "step 200, entropy loss: 0.270370, l2_loss: 110.623703, total loss: 0.278113\n",
      "0.96\n",
      "step 300, entropy loss: 0.229614, l2_loss: 112.309006, total loss: 0.237476\n",
      "0.98\n",
      "step 400, entropy loss: 0.319698, l2_loss: 113.341942, total loss: 0.327632\n",
      "0.97\n",
      "step 500, entropy loss: 0.342886, l2_loss: 114.239761, total loss: 0.350883\n",
      "0.93\n",
      "step 600, entropy loss: 0.070974, l2_loss: 114.993027, total loss: 0.079024\n",
      "0.99\n",
      "step 700, entropy loss: 0.186475, l2_loss: 115.722214, total loss: 0.194575\n",
      "0.96\n",
      "step 800, entropy loss: 0.047063, l2_loss: 116.389946, total loss: 0.055210\n",
      "0.98\n",
      "step 900, entropy loss: 0.095765, l2_loss: 116.857338, total loss: 0.103945\n",
      "0.98\n",
      "step 1000, entropy loss: 0.037860, l2_loss: 117.442886, total loss: 0.046081\n",
      "0.98\n",
      "0.977\n",
      "step 1100, entropy loss: 0.182006, l2_loss: 117.963310, total loss: 0.190263\n",
      "0.96\n",
      "step 1200, entropy loss: 0.055549, l2_loss: 118.401588, total loss: 0.063837\n",
      "1.0\n",
      "step 1300, entropy loss: 0.034805, l2_loss: 118.838341, total loss: 0.043123\n",
      "0.99\n",
      "step 1400, entropy loss: 0.111607, l2_loss: 119.268135, total loss: 0.119956\n",
      "0.98\n",
      "step 1500, entropy loss: 0.021444, l2_loss: 119.705681, total loss: 0.029823\n",
      "1.0\n",
      "step 1600, entropy loss: 0.120279, l2_loss: 120.077843, total loss: 0.128684\n",
      "0.99\n",
      "step 1700, entropy loss: 0.050404, l2_loss: 120.434090, total loss: 0.058835\n",
      "0.98\n",
      "step 1800, entropy loss: 0.026644, l2_loss: 120.784035, total loss: 0.035099\n",
      "1.0\n",
      "step 1900, entropy loss: 0.099541, l2_loss: 121.112755, total loss: 0.108019\n",
      "0.98\n",
      "step 2000, entropy loss: 0.065476, l2_loss: 121.473320, total loss: 0.073980\n",
      "0.99\n",
      "0.9849\n",
      "step 2100, entropy loss: 0.080916, l2_loss: 121.800636, total loss: 0.089442\n",
      "0.99\n",
      "step 2200, entropy loss: 0.126435, l2_loss: 122.103622, total loss: 0.134982\n",
      "0.97\n",
      "step 2300, entropy loss: 0.066154, l2_loss: 122.341736, total loss: 0.074718\n",
      "0.99\n",
      "step 2400, entropy loss: 0.034884, l2_loss: 122.581932, total loss: 0.043465\n",
      "0.99\n",
      "step 2500, entropy loss: 0.080830, l2_loss: 122.808952, total loss: 0.089427\n",
      "0.99\n",
      "step 2600, entropy loss: 0.022632, l2_loss: 123.095428, total loss: 0.031248\n",
      "0.99\n",
      "step 2700, entropy loss: 0.028080, l2_loss: 123.392807, total loss: 0.036718\n",
      "1.0\n",
      "step 2800, entropy loss: 0.083049, l2_loss: 123.674347, total loss: 0.091706\n",
      "0.98\n",
      "step 2900, entropy loss: 0.035474, l2_loss: 123.910194, total loss: 0.044148\n",
      "0.99\n",
      "step 3000, entropy loss: 0.026998, l2_loss: 124.142548, total loss: 0.035688\n",
      "1.0\n",
      "0.9867\n"
     ]
    }
   ],
   "source": [
    "# Train\n",
    "for step in range(3000):\n",
    "  batch_xs, batch_ys = mnist.train.next_batch(100)\n",
    "  lr = 0.05\n",
    "  _, loss, l2_loss_value, total_loss_value = sess.run(\n",
    "               [train_step, cross_entropy, l2_loss, total_loss], \n",
    "               feed_dict={x: batch_xs, y_: batch_ys, learning_rate:lr, keep_prob:0.5})\n",
    "  \n",
    "  if (step+1) % 100 == 0:\n",
    "    print('step %d, entropy loss: %f, l2_loss: %f, total loss: %f' % \n",
    "            (step+1, loss, l2_loss_value, total_loss_value))\n",
    "    # Test trained model\n",
    "    correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))\n",
    "    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n",
    "    print(sess.run(accuracy, feed_dict={x: batch_xs, y_: batch_ys, keep_prob:0.5}))\n",
    "  if (step+1) % 1000 == 0:\n",
    "    print(sess.run(accuracy, feed_dict={x: mnist.test.images,\n",
    "                                    y_: mnist.test.labels, keep_prob:0.5}))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "验证我们模型在测试数据上的准确率"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.9868\n"
     ]
    }
   ],
   "source": [
    "# Test trained model\n",
    "correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))\n",
    "accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n",
    "print(sess.run(accuracy, feed_dict={x: mnist.test.images,\n",
    "                                      y_: mnist.test.labels, keep_prob:0.5}))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "毫无疑问，这个模型是一个非常简陋，性能也不理想的模型。目前只能达到92%左右的准确率。\n",
    "接下来，希望大家利用现有的知识，将这个模型优化至98%以上的准确率。\n",
    "Hint：\n",
    "- 卷积\n",
    "- 池化\n",
    "- 激活函数\n",
    "- 正则化\n",
    "- 初始化\n",
    "- 摸索一下各个超参数\n",
    "  - 卷积kernel size\n",
    "  - 卷积kernel 数量\n",
    "  - 学习率\n",
    "  - 正则化惩罚因子\n",
    "  - 最好每隔几个step就对loss、accuracy等等进行一次输出，这样才能有根据地进行调整"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
